'use strict';

const url = require("url")
const cookie = require('cookie');
const userInfoService = require('../services/user-info');
const {env} = require("@strapi/utils");

module.exports = {
  async getUserInfo(ctx) {
    const request = ctx.request;
    const {query} = url.parse(request.url, true)
    const callback = query.callback;
    const cookies = cookie.parse(request.header.cookie || '');
    const token = cookies.token || request.header.authorization?.replace('Bearer', '');
    const noUserInfo = await userInfoService.noUserInfo(callback);

    ctx.set('Content-Type', 'text/javascript; charset=utf-8');

    if (!token) {
      return ctx.send(noUserInfo);
    }
    ctx.request.header.authorization = `Bearer ${token}`;

    try {
      const {id} = await strapi.plugins['users-permissions'].services.jwt.getToken(ctx);
      ctx.state.user = await strapi.plugins['users-permissions'].services.user.fetch(id, {populate: "*"});
    } catch (err) {
      return ctx.send(noUserInfo);
    }

    if (!ctx.state.user) {
      return ctx.send(noUserInfo);
    }

    const userInfo = await userInfoService.processUserInfo(ctx.state.user);
    const scriptStr = `${callback}(${JSON.stringify(userInfo)})`

    return ctx.send(scriptStr);
  },
  async getUserLogout(ctx) {
    const request = ctx.request;
    const {query} = url.parse(request.url, true)
    const callback = query.callback;

    const scriptStr = `${callback}(${JSON.stringify({
      code: 1,
      reload_page: 0,
      js_src: ['/static/js/logout.js']
    })})`
    ctx.set('Content-Type', 'text/javascript; charset=utf-8');

    return ctx.send(scriptStr);
  }
};
